#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Mock微信接口服务
基于Flask框架实现的企业微信API Mock服务
"""

import os
import logging
from datetime import datetime
from flask import Flask, request, jsonify
from flask_cors import CORS

# 导入各个接口模块
from api.gettoken import gettoken_bp
from api.kf_account_list import kf_account_list_bp
from api.kf_sync_msg import kf_sync_msg_bp
from api.kf_sync_service_state import kf_sync_service_state_bp
from api.kf_service_state_get import kf_service_state_get_bp
from api.kf_service_state_trans import kf_service_state_trans_bp
from api.kf_send_msg import kf_send_msg_bp
from api.kf_servicer_list import kf_servicer_list_bp
from api.webhook_simulator import webhook_simulator_bp

# 导入数据管理模块
from utils.data_manager import DataManager
from utils.logger import setup_logger
from utils.config import Config



def create_app():
    """创建Flask应用"""
    app = Flask(__name__)
    # 确保JSON响应不进行ASCII转义，便于中文显示
    app.config['JSON_AS_ASCII'] = False
    
    # 加载配置
    config = Config()
    app.config.from_object(config)
    
    # 设置CORS
    CORS(app)
    
    # 设置日志
    setup_logger()
    logger = logging.getLogger(__name__)
    
    # 初始化数据管理器
    data_manager = DataManager()
    app.data_manager = data_manager
    
    # 注册蓝图
    app.register_blueprint(gettoken_bp)
    app.register_blueprint(kf_account_list_bp)
    app.register_blueprint(kf_sync_msg_bp)
    app.register_blueprint(kf_sync_service_state_bp)
    app.register_blueprint(kf_service_state_get_bp)
    app.register_blueprint(kf_service_state_trans_bp)
    app.register_blueprint(kf_send_msg_bp)
    app.register_blueprint(kf_servicer_list_bp)
    app.register_blueprint(webhook_simulator_bp)
    
    # 全局请求日志中间件
    @app.before_request
    def log_request():
        """记录请求日志"""
        logger.info(f"请求: {request.method} {request.path} - 参数: {dict(request.args)}")
        logger.info(f"Content-Type: {request.content_type}")
        try:
            raw_body = request.get_data(cache=True)
            logger.info(f"原始请求体bytes前200: {raw_body[:200]!r}")
            # 强制使用UTF-8编码，避免Windows系统默认编码问题
            charset = (request.mimetype_params or {}).get('charset') or 'utf-8'
            if charset.lower() not in ['utf-8', 'utf8']:
                charset = 'utf-8'
            try:
                body_text = raw_body.decode(charset, errors='replace')
            except Exception:
                body_text = raw_body.decode('utf-8', errors='replace')
            logger.info(f"原始请求体文本({charset}): {body_text}")
        except Exception as e:
            logger.warning(f"读取原始请求体失败: {e}")
        if request.is_json:
            try:
                logger.info(f"请求体JSON解析: {request.get_json(silent=True)}")
            except Exception as e:
                logger.warning(f"JSON解析异常: {e}")
    
    @app.after_request
    def log_response(response):
        """记录响应日志"""
        logger.info(f"响应: {response.status_code} - {response.get_data(as_text=True)[:200]}")
        return response
    
    # 健康检查接口
    @app.route('/health', methods=['GET'])
    def health_check():
        """健康检查接口"""
        return jsonify({
            "status": "healthy",
            "service": "mock-wx-api",
            "version": "1.0.0",
            "timestamp": datetime.now().isoformat()
        })
    
    # 状态监控接口
    @app.route('/status', methods=['GET'])
    def status():
        """状态监控接口"""
        stats = data_manager.get_stats()
        return jsonify({
            "service": "mock-wx-api",
            "version": "1.0.0",
            "status": "running",
            "timestamp": datetime.now().isoformat(),
            "stats": stats
        })
    
    # 错误处理
    @app.errorhandler(404)
    def not_found(error):
        logger.warning(f"404错误: {request.path}")
        return jsonify({
            "errcode": 404,
            "errmsg": "接口不存在"
        }), 404
    
    @app.errorhandler(500)
    def internal_error(error):
        logger.error(f"500错误: {error}")
        return jsonify({
            "errcode": 500,
            "errmsg": "服务器内部错误"
        }), 500
    
    logger.info("Mock微信接口服务启动成功")
    return app


if __name__ == '__main__':
    app = create_app()
    app.run(
        host=os.getenv('MOCK_WX_HOST', 'localhost'),
        port=int(os.getenv('MOCK_WX_PORT', 8084)),
        debug=os.getenv('MOCK_WX_DEBUG', 'true').lower() == 'true',
        use_reloader=True,
        reloader_type='auto',
        reloader_interval=1
    )
